package com.glsc.ngateway.platform.controller.it;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.enums.PageConstant;
import com.glsc.ngateway.common.api.platform.dto.it.ParamSearchAppDto;
import com.glsc.ngateway.common.api.platform.dto.it.ParamSearchSystemDto;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItApplicationDetail;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItOperation;
import com.glsc.ngateway.platform.aspect.UserCache;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.platform.service.it.OperationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/it")
@Api(value = "操作控制", tags = {"操作控制"})
public class OperationController {

    private static final Logger logger = LoggerFactory.getLogger(OperationController.class);

    @Autowired
    private OperationService operationService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserCache userCache;
    @Autowired
    private UserService userService;

    //查询全部应用明细，不分页
    @RequestMapping(method = RequestMethod.GET, value = "/app/listAll")
    @ApiOperation(value = "查询全部应用明细清单(无分权)", notes = "查询全部应用明细清单(无分权)")
    public PlatformResponse<List<ItApplicationDetail>> queryAllAppList() {
        List<ItApplicationDetail> result = operationService.queryAllAppList();
        return PlatformResponse.successData(result);
    }
    // 查询应用明细清单(无分权)
    @RequestMapping(method = RequestMethod.POST, value = "/app/search")
    @ApiOperation(value = "查询应用明细清单(无分权)", notes = "查询应用明细清单(无分权)")
    public PlatformResponse<Page<ItApplicationDetail>> queryAppList(@RequestBody ParamSearchAppDto params) {
        if (params.getPageNo() == null) {
            params.setPageNo(PageConstant.PageNo);
        }
        if (params.getPageSize() == null) {
            params.setPageSize(PageConstant.PageSize);
        }
        Page<ItApplicationDetail> result = operationService.queryAppByMxId(params.getPageNo(), params.getPageSize(),params);
        return PlatformResponse.successData(result);
    }

    /*
     * 删除应用明细
     */
    @RequestMapping(method = RequestMethod.POST, value = "/app/delete")
    @ApiOperation(value = "删除应用明细", notes = "删除应用明细")
    public PlatformResponse<Void> deleteShowmx(@RequestBody String mxId) {
        if (StringUtils.isEmpty(mxId)) {
            return PlatformResponse.failedMsg("deleteShowmx接口，mxId为空。");
        }
        JSONObject jsonObject = (JSONObject) JSON.parse(mxId);
        String id = jsonObject.getString("mxId");
        if (StringUtils.isNotEmpty(id)) {
            operationService.deleteShowmx(id);
        }
        return PlatformResponse.successMsg("应用明细删除成功");
    }

    /*
     * 提交或修改应用明细
     */
    @RequestMapping(method = RequestMethod.POST, value = "/app/addOrUpdate")
    @ApiOperation(value = "提交或修改应用明细", notes = "提交或修改应用明细")
    public PlatformResponse<Void> addOrUpdateShowmx(@RequestBody ItApplicationDetail itApplicationDetail) {
        if (StringUtils.isEmpty(itApplicationDetail.getMxName())) {
            return PlatformResponse.failedMsg("addOrUpdateShowmx接口，名称为空。");
        }
        PlatformUserDto user = userCache.get(request);
        operationService.addOrUpdateShowmx(itApplicationDetail, user.getUserid());
        return PlatformResponse.successMsg("创建或修改成功");
    }


    @RequestMapping(method = RequestMethod.POST, value = "/system/search")
    @ApiOperation(value = "列表", notes = "列表")
    public PlatformResponse<Page<ItOperation>> queryOpeList(@RequestBody ParamSearchSystemDto params) {
        if (params.getPageNo() == null) {
            params.setPageNo(PageConstant.PageNo);
        }
        if (params.getPageSize() == null) {
            params.setPageSize(PageConstant.PageSize);
        }

        PlatformUserDto user = userCache.get(request);
        String userId = user.getUserid();
        Set<String> roleNames = new HashSet<>(user.getRoles());
        if ("itadmin".equals(user.getUsername()) || roleNames.contains("itadmin")) {
            userId = null;
        }
        Page<ItOperation> result = operationService.queryOperationByUserId(params.getPageNo(), params.getPageSize(), userId,params);
        return PlatformResponse.successData(result);
    }


    /**
     * 提交或修改系统运行设备
     */
    @RequestMapping(method = RequestMethod.POST, value = "/system/addOrUpdate")
    @ApiOperation(value = "提交或修改系统运行设备", notes = "提交或修改系统运行设备")
    public PlatformResponse<Void> addOrUpdateOperation(@RequestBody ItOperation itOperation) {
        if (StringUtils.isEmpty(itOperation.getOpName())) {
            return PlatformResponse.failedMsg("addOrUpdateOperation接口，名称为空。");
        }
        if (StringUtils.isEmpty(String.valueOf(itOperation.getOpStyle()))) {
            return PlatformResponse.failedMsg("addOrUpdateOperation接口，业务类型为空。");
        }
        PlatformUserDto user = userCache.get(request);
        operationService.addOrUpdateOperation(itOperation, user.getUserid());
        return PlatformResponse.successMsg("创建或修改成功");
    }

    /*
     * 删除设备
     */
    @RequestMapping(method = RequestMethod.POST, value = "/system/delete")
    @ApiOperation(value = "删除设备", notes = "删除设备")
    public PlatformResponse<Void> deleteOperation(@RequestBody String opId) {
        if (StringUtils.isEmpty(opId)) {
            return PlatformResponse.failedMsg("deleteOperation接口，opId为空。");
        }
        JSONObject jsonObject = (JSONObject) JSON.parse(opId);
        String id = jsonObject.getString("opId");
        if (StringUtils.isNotEmpty(id)) {
            operationService.deleteOperation(id);
        }
        return PlatformResponse.successMsg("系统删除成功");
    }

//
//    // 查询应用明细清单(根据用户名分权)
//    @RequestMapping(value = "/queryShowList", method = {RequestMethod.GET, RequestMethod.POST})
//    public Object queryShowList(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        String userId = (String) request.getAttribute("currentUserId");
//        List<Map<String, Object>> result = operationService.queryShowByUserId(userId);
//
//        // 整理输出信息
//        JsonResult jsonResult = new JsonResult();
//        jsonResult.saveResultSet(result);
//        return jsonResult;
//    }
//
//    // 查询业务系统清单
//    @RequestMapping(value = "/querySystemList", method = {RequestMethod.GET, RequestMethod.POST})
//    public Object querySystemList(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        String opId = (String) request.getAttribute("currentOpId");
//        List<Map<String, Object>> result = operationService.querySystemListByOpId();
//
//        // 整理输出信息
//        JsonResult jsonResult = new JsonResult();
//        jsonResult.saveResultSet(result);
//        return jsonResult;
//    }
//
//    // 查询应用ID清单
//    @RequestMapping(value = "/queryOpidList", method = {RequestMethod.GET, RequestMethod.POST})
//    public Object queryOpidList(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        String opUser = (String) request.getAttribute("currentUserId");
//        List<Map<String, Object>> result = operationService.queryOpidByOpUser(opUser);
//
//        // 整理输出信息
//        JsonResult jsonResult = new JsonResult();
//        jsonResult.saveResultSet(result);
//        return jsonResult;
//    }
//
//    ////////////////////////////////////////////////////////////////////////
//    // 查询详情页面
//    @RequestMapping(value = "/queryMoreViewList", method = {RequestMethod.GET, RequestMethod.POST})
//    public Object queryMoreViewList(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        String opId = (String) request.getParameter("opId");
//        List<Map<String, Object>> result = operationService.queryOpViewByOpId(opId);
//
//        // 整理输出信息
//        JsonResult jsonResult = new JsonResult();
//        jsonResult.saveResultSet(result);
//        return jsonResult;
//    }
//////////////////////////////////////////////////////////////////////////////


}